package com.jsmtr.rms.controller;

import cn.hutool.core.date.CalendarUtil;
import cn.ktjk.DataTableUtile.DataTable.DataRow;
import cn.ktjk.DataTableUtile.DataTable.DataTable;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.*;
import com.jsmtr.rms.utils.*;
import jxl.Sheet;
import jxl.Workbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/Do/BS")
public class DoBSController {

    @Resource
    private IUtilService utilService;
    @Resource
    private IDoBSService bsService;
    @Resource
    private IProjectService projectService;
    @Resource
    private IDoSZService szService;


    //[start] 考场管理

    //[start] 考场列表

    @RequestMapping("/room")
    public String room() {
        return "/Do/Bs/room";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getrooms")
    public void getrooms(HttpServletRequest request, HttpServletResponse response, DoBSRoom room) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));

            Map<String, Object> map = bsService.getBSRooms(page, perpage, room);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 0;
                for (DoBSRoom _room : (List<DoBSRoom>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id='cb_" + _room.getId() + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td>" + _room.getName() + "</td>");
                    result.append("<td>" + _room.getNickname() + "</td>");
                    result.append("<td>" + _room.getStartnum() + "</td>");
                    result.append("<td>" + _room.getAllcount() + "</td>");
                    result.append("<td>" + _room.getAddress() + "</td>");
                    result.append("<td>" + _room.getState() + "</td>");
                    result.append("<td>" + _room.getPriority() + "</td></tr>");
                    num++;
                }
            } else {
                result.append("<tr><td colspan='8'>无符合条件的信息</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='8'>读取信息失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/getroomsLayuiJson")
    public LayuiDataTableResultBean getroomsLayuiJson(HttpServletRequest request, HttpServletResponse response, DoBSRoom room) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            Map<String, Object> map = bsService.getBSRooms(page, limit, room);

            double pageCount = (Double) map.get("pageCount");

            JSONArray jsonArray = new JSONArray();

            if (pageCount != 0){
                Object object = map.get("list");
                int num = 1;
                for (DoBSRoom _room : (List<DoBSRoom>) object) {
                    JSONObject jsonObject = JSONObject.fromObject(_room);

                    jsonObject.put("ids", "cb_" + _room.getId());
                    jsonObject.put("id",limit * (page - 1) + num);

                    jsonArray.add(jsonObject);
                    num++;
                }
            }
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double)map.get("count")).intValue());
            result.setData(jsonArray);

            return result;

        }catch (Exception e){
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
    //[end]

    //[start] 添加考场

    @RequestMapping("/addroom")
    public String addroom() {
        return "/Do/Bs/roomadd";
    }

    @RequestMapping(value = "/AddRoomAction", method = RequestMethod.POST)
    public void AddRoomAction(HttpServletRequest request, HttpServletResponse response, DoBSRoom room) {
        try {
            String address = request.getParameter("address").trim();

            if (bsService.getRoomByAddress(address) == null) {
                room.setId(UUID.randomUUID().toString());
                utilService.addObject(room);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "考场地址重复", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }


    @RequestMapping("/exportsign")
    public void exportsign(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            String[] jname = request.getParameter("jname").split(",");
            if (jname.length != 0 && jname != null && jname[0] != "") {
                HSSFWorkbook workbook = new HSSFWorkbook();
                codedFileName = java.net.URLEncoder.encode("笔试签到表", "UTF-8");

                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
                // 新建map
                Map<String, List<Object[]>> signMap = new HashMap<>();

                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                String pid = request.getParameter("pid").trim();
                List<ProjectInfoJobs> projectJobs = utilService.getProjectJobs(pid);

                String fid = request.getParameter("fid").trim();
                ProjectInfo project = projectService.getProjectInfo(fid);
                List<Object[]> objs = bsService.getBsUsers(fid, jname, project.getRecruittype());
                Set set = new HashSet();
                for (Object[] obj : objs) {
                    set.add(obj[3].toString());
                }
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    List<Object[]> signList = new ArrayList<Object[]>();
                    String str = iterator.next();
                    for (Object[] objects : objs) {
                        if (str.equals(objects[3].toString())) {
                            signList.add(objects);
                        }
                    }
                    signMap.put(str.replaceAll(":", ".").
                            replaceAll("\\d{4}-", "").
                            replaceAll("\\(", "").replaceAll("\\)", ""), signList);
                }
                for (Map.Entry<String, List<Object[]>> kind : signMap.entrySet()) {
                    int i = 2;
                    HSSFSheet sheet = workbook.createSheet(kind.getKey().toString());
                    //[start] 笔试签到表头

                    HSSFRow headerrow = sheet.createRow(0);//创建一行
                    headerrow.setHeightInPoints(30);
                    HSSFCell headcel = headerrow.createCell(0);
                    headcel.setCellStyle(cellStyle);

                    headcel.setCellValue(new HSSFRichTextString(kind.getValue().get(0)[3].toString().split("\\(")[0] + "考室人员签到表") + "-" + kind.getValue().get(0)[4].toString());
                    CellRangeAddress callRangeAddress = new CellRangeAddress(0, 0, 0, 4);//起始行,结束行,起始列,结束列

                    sheet.addMergedRegion(callRangeAddress);

                    HSSFRow headrow = sheet.createRow(1);//创建一行
                    HSSFCell headcel0 = headrow.createCell(0);
                    headcel0.setCellValue(new HSSFRichTextString("序号"));
                    headcel0.setCellStyle(cellStyle);
                    HSSFCell headcel1 = headrow.createCell(1);
                    headcel1.setCellValue(new HSSFRichTextString("姓名"));
                    headcel1.setCellStyle(cellStyle);
                    HSSFCell headcel2 = headrow.createCell(2);
                    headcel2.setCellValue(new HSSFRichTextString("身份证号"));
                    headcel2.setCellStyle(cellStyle);
                    HSSFCell headcel3 = headrow.createCell(3);
                    headcel3.setCellValue(new HSSFRichTextString("应聘岗位"));
                    headcel3.setCellStyle(cellStyle);
                    HSSFCell headcel4 = headrow.createCell(4);
                    headcel4.setCellValue(new HSSFRichTextString("准考证号"));
                    headcel4.setCellStyle(cellStyle);
                    HSSFCell headcel5 = headrow.createCell(5);
                    headcel5.setCellValue(new HSSFRichTextString("签到"));
                    headcel5.setCellStyle(cellStyle);


                    sheet.setColumnWidth(0, 10 * 256);
                    sheet.setColumnWidth(1, 10 * 256);
                    sheet.setColumnWidth(2, 30 * 256);
                    sheet.setColumnWidth(2, 30 * 256);
                    sheet.setColumnWidth(3, 20 * 256);
                    sheet.setColumnWidth(4, 10 * 256);
                    Integer[] outIndex=new Integer[]{0,1,4,2};
                    for (Object[] obj : kind.getValue()) {
                        HSSFRow row = sheet.createRow(i);//创建一行
                        HSSFCell cell = row.createCell(0);//创建一列
                        //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellType(CellType.STRING);
                        cell.setCellStyle(cellStyle);
                        cell.setCellValue(i - 1);
                        for (int j = 0; j < outIndex.length; j++) {
                            cell = row.createCell(j + 1);
                           // cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                            cell.setCellType(CellType.STRING);
                            cell.setCellStyle(cellStyle);
                            cell.setCellValue(new HSSFRichTextString(obj[outIndex[j]] == null ? "" : obj[outIndex[j]].toString()));
                        }
                        i++;
                    }
                }
                fOut = response.getOutputStream();
                workbook.write(fOut);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }


    @RequestMapping("/exportpeopleinfo")
    public void exportpeopleinfo(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            String[] jname = request.getParameter("jname").split(",");
            if (jname.length != 0 && jname != null && jname[0] != "") {
                HSSFWorkbook workbook = new HSSFWorkbook();
                codedFileName = java.net.URLEncoder.encode("人员信息表", "UTF-8");

                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
                // 新建map
                Map<String, List<Object[]>> signMap = new HashMap<>();

                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                String pid = request.getParameter("pid").trim();
                List<ProjectInfoJobs> projectJobs = utilService.getProjectJobs(pid);

                String fid = request.getParameter("fid").trim();
                ProjectInfo project = projectService.getProjectInfo(fid);
                List<Object[]> objs = bsService.getBsUsers(fid, jname, project.getRecruittype());
                Set set = new HashSet();
                for (Object[] obj : objs) {
                    set.add(obj[3].toString());
                }
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    List<Object[]> signList = new ArrayList<Object[]>();
                    String str = iterator.next();
                    for (Object[] objects : objs) {
                        if (str.equals(objects[3].toString())) {
                            signList.add(objects);
                        }
                    }
                    signMap.put(str.replaceAll(":", ".").
                            replaceAll("\\d{4}-", "").
                            replaceAll("\\(", "").replaceAll("\\)", ""), signList);
                }
                for (Map.Entry<String, List<Object[]>> kind : signMap.entrySet()) {
                    int i = 2;
                    HSSFSheet sheet = workbook.createSheet(kind.getKey().toString());
                    //[start] 笔试签到表头

                    HSSFRow headerrow = sheet.createRow(0);//创建一行
                    headerrow.setHeightInPoints(30);
                    HSSFCell headcel = headerrow.createCell(0);
                    headcel.setCellStyle(cellStyle);

                    headcel.setCellValue(new HSSFRichTextString(kind.getValue().get(0)[3].toString().split("\\(")[0] + "考室人员信息表") + "-" + kind.getValue().get(0)[4].toString());

                    CellRangeAddress callRangeAddress = new CellRangeAddress(0, 0, 0, 3);//起始行,结束行,起始列,结束列

                    sheet.addMergedRegion(callRangeAddress);

                    HSSFRow headrow = sheet.createRow(1);//创建一行
                    HSSFCell headcel0 = headrow.createCell(0);
                    headcel0.setCellValue(new HSSFRichTextString("序号"));
                    headcel0.setCellStyle(cellStyle);
                    HSSFCell headcel1 = headrow.createCell(1);
                    headcel1.setCellValue(new HSSFRichTextString("姓名"));
                    headcel1.setCellStyle(cellStyle);
                    HSSFCell headcel2 = headrow.createCell(2);
                    headcel2.setCellValue(new HSSFRichTextString("身份证号"));
                    headcel2.setCellStyle(cellStyle);
                    HSSFCell headcel3 = headrow.createCell(3);
                    headcel3.setCellValue(new HSSFRichTextString("准考证号"));
                    headcel3.setCellStyle(cellStyle);


                    sheet.setColumnWidth(0, 10 * 256);
                    sheet.setColumnWidth(1, 10 * 256);
                    sheet.setColumnWidth(2, 30 * 256);
                    sheet.setColumnWidth(3, 20 * 256);

                    for (Object[] obj : kind.getValue()) {
                        HSSFRow row = sheet.createRow(i);//创建一行
                        HSSFCell cell = row.createCell(0);//创建一列
                        //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellValue(String.valueOf(CellType.STRING));
                        cell.setCellStyle(cellStyle);
                        cell.setCellValue(i - 1);
                        for (int j = 0; j < 3; j++) {
                            cell = row.createCell(j + 1);
                           // cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                            cell.setCellValue(String.valueOf(CellType.STRING));
                            cell.setCellStyle(cellStyle);
                            cell.setCellValue(new HSSFRichTextString(obj[j] == null ? "" : obj[j].toString()));
                        }
                        i++;
                    }
                }
                fOut = response.getOutputStream();
                workbook.write(fOut);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }


    @RequestMapping("/exportseatlabel")
    public void exportseatlabel(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            String[] jname = request.getParameter("jname").split(",");
            if (jname.length != 0 && jname != null && jname[0] != "") {
                HSSFWorkbook workbook = new HSSFWorkbook();
                codedFileName = java.net.URLEncoder.encode("座位标签表", "UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
                // 新建map
                Map<String, List<Object[]>> signMap = new HashMap<>();

                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                String pid = request.getParameter("pid").trim();
                List<ProjectInfoJobs> projectJobs = utilService.getProjectJobs(pid);

                String fid = request.getParameter("fid").trim();
                ProjectInfo project = projectService.getProjectInfo(fid);
                List<Object[]> objs = bsService.getBsUsers(fid, jname, project.getRecruittype());
                Set set = new HashSet();
                for (Object[] obj : objs) {
                    set.add(obj[3].toString());
                }
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    List<Object[]> signList = new ArrayList<Object[]>();
                    String str = iterator.next();
                    for (Object[] objects : objs) {
                        if (str.equals(objects[3].toString())) {
                            signList.add(objects);
                        }
                    }
                    signMap.put(str.replaceAll(":", ".").
                            replaceAll("\\d{4}-", "").
                            replaceAll("\\(", "").replaceAll("\\)", ""), signList);
                }
                for (Map.Entry<String, List<Object[]>> kind : signMap.entrySet()) {
                    int i = 1;
                    HSSFSheet sheet = workbook.createSheet(kind.getKey().toString());
                    //[start] 笔试签到表头

                    HSSFRow headerrow = sheet.createRow(0);//创建一行
                    headerrow.setHeightInPoints(30);
                    HSSFCell headcel = headerrow.createCell(0);
                    headcel.setCellStyle(cellStyle);

                    headcel.setCellValue(new HSSFRichTextString(kind.getValue().get(0)[3].toString().split("\\(")[0] + "考室") + "-" + kind.getValue().get(0)[4].toString());
                    CellRangeAddress callRangeAddress = new CellRangeAddress(0, 0, 0, 1);//起始行,结束行,起始列,结束列

                    sheet.addMergedRegion(callRangeAddress);

                    CellStyle cs = workbook.createCellStyle();
                    HSSFFont redFont = workbook.createFont();
                    //设置字体大小
                    redFont.setFontHeightInPoints((short) 11);
                    redFont.setFontName("宋体");
                    cs.setFont(redFont);
                    cs.setWrapText(true);
                    cs.setAlignment(HorizontalAlignment.JUSTIFY);
                    cs.setVerticalAlignment(VerticalAlignment.TOP);

                    sheet.setColumnWidth(0, 50 * 256);
                    sheet.setColumnWidth(1, 50 * 256);

                    List<Object[]> list = kind.getValue();

                    for (int j = 0; j < list.size(); j = j + 2) {
                        HSSFRow row = sheet.createRow(i);//创建一行
                        row.setHeightInPoints(72);
                        HSSFCell cell = row.createCell(0);//创建一列
                        cell.setCellStyle(cs);
                        String str = "\r\n座位号：" + new HSSFRichTextString(list.get(j)[5] == null ? "" : list.get(j)[5].toString()) +
                                "   考试时间：" + new HSSFRichTextString(list.get(j)[3] == null ? "" : list.get(j)[3].toString().split("\\(")[1].replace(")", "")) +
                                "\r\n" +
                                "\r\n" +
                                "准考证号：" + new HSSFRichTextString(list.get(j)[2] == null ? "" : list.get(j)[2].toString());
                        cell.setCellValue(str);

                        HSSFCell cell1 = row.createCell(1);//创建一列
                        cell1.setCellStyle(cs);

                        if (j + 1 < list.size()) {
                            String str1 = "\r\n座位号：" + new HSSFRichTextString(list.get(j + 1)[5] == null ? "" : list.get(j + 1)[5].toString()) +
                                    "   考试时间：" + new HSSFRichTextString(list.get(j + 1)[3] == null ? "" : list.get(j + 1)[3].toString().split("\\(")[1].replace(")", "")) +
                                    "\r\n" +
                                    "\r\n" +
                                    "准考证号：" + new HSSFRichTextString(list.get(j + 1)[2] == null ? "" : list.get(j + 1)[2].toString());
                            cell1.setCellValue(str1);
                        }
                        i++;
                    }
                }
                fOut = response.getOutputStream();
                workbook.write(fOut);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }

    //[end]

    //[start] 修改考场

    @RequestMapping("/editroom")
    public String editroom(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("room", bsService.getRoomById(request.getParameter("id").trim()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Bs/roomedit";
    }

    @RequestMapping(value = "/EditRoomAction", method = RequestMethod.POST)
    public void EditRoomAction(HttpServletRequest request, HttpServletResponse response, DoBSRoom room) {
        try {
            String id = request.getParameter("id").trim();
            String name = request.getParameter("name").trim();
            DoBSRoom _room1 = bsService.getRoomById(id);
            DoBSRoom _room2 = bsService.getRoomByName(name);
            if (_room2 != null && !_room1.getId().equals(_room2.getId())) {
                utilService.printJsonResult(false, "考场名称重复", "no", response);
            } else {
                _room1.setAddress(room.getAddress());
                _room1.setAllcount(room.getAllcount());
                _room1.setName(room.getName());
                _room1.setNickname(room.getNickname());
                _room1.setStartnum(room.getStartnum());
                _room1.setState(room.getState());
                _room1.setPriority(room.getPriority());
                utilService.editObject(_room1);
                utilService.printJsonResult(true, "操作成功", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 删除考场

    @SuppressWarnings({"unchecked", "rawtypes"})
    @RequestMapping(value = "/DelRoomAction", method = RequestMethod.POST)
    public void DelRoomAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");
            if (ids == null) {
                utilService.printJsonResult(false, "请选择要删除的信息", "no", response);
            } else {
                List delList = new ArrayList();
                List<DoBSRoom> rooms = bsService.getRooms(ids);
                for (DoBSRoom room : rooms) {
                    List<DoBSExam> exams = bsService.getExams(room.getId());
                    delList.addAll(exams);
                }
                delList.addAll(rooms);

                utilService.delList(delList);
                utilService.printJsonResult(true, "操作成功", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[end]

    //[start] 考试管理

    //[start] 考试列表
    @RequestMapping("/exam")
    public String exam(Model model) {
        try {
            List<DoBSRoom> rooms = bsService.getRooms();
            StringBuilder roomsb = new StringBuilder();
            for (DoBSRoom room : rooms) {
                roomsb.append("<option value='" + room.getId() + "'>" + room.getName() + "</option>");
            }
            model.addAttribute("room", roomsb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Bs/exam";
    }


    @SuppressWarnings("unchecked")
    @RequestMapping("/getexams")
    public void getexams(HttpServletRequest request, HttpServletResponse response, DoBSExam exam) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));

            Map<String, Object> map = bsService.getBSExams(page, perpage, exam);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 0;
                for (Object[] _exam : (List<Object[]>) object) {
                    //m.id,m.roomid,m.name,m.starttime,m.endtime,r.name,r.allcount
                    result.append("<tr><td><input type=\"checkbox\" id='cb_" + _exam[0] + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td>" + _exam[2] + "</td>");
                    result.append("<td>" + _exam[5] + "</td>");
                    result.append("<td>" + _exam[6] + "</td>");
                    result.append("<td>" + _exam[3] + "</td>");
                    result.append("<td>" + _exam[4] + "</td>");
                    num++;
                }
            } else {
                result.append("<tr><td colspan='7'>无符合条件的信息</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='7'>读取信息失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/getexamsLayuiJson")
    public LayuiDataTableResultBean getexamsLayuiJson(HttpServletRequest request, HttpServletResponse response, DoBSExam exam) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            Map<String, Object> map = bsService.getBSExams(page, limit, exam);

            double pageCount = (Double) map.get("pageCount");

            JSONArray jsonArray = new JSONArray();

            if (pageCount != 0){
                Object object = map.get("list");
                int num = 1;
                for (Object[] _exam : (List<Object[]>) object) {
                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("ids","cb_" + _exam[0]);
                    jsonObject.put("id",limit * (page - 1) + num);
                    jsonObject.put("name", _exam[5]);
                    jsonObject.put("addname",_exam[2]);
                    jsonObject.put("startnum",_exam[6]);
                    jsonObject.put("starttime",_exam[3]);
                    jsonObject.put("endtime",_exam[4]);

                    jsonArray.add(jsonObject);
                    num++;
                }
            }
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double)map.get("count")).intValue());
            result.setData(jsonArray);

            return result;

        }catch (Exception e){
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //获取考试信息
    @RequestMapping("/getrexams")
    public void getrexams(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            DoBSRoom room = bsService.getRoomById(id);
            List<DoBSExam> exams = bsService.getExams(id);
            StringBuilder result = new StringBuilder();
            for (DoBSExam exam : exams) {
                result.append("<option value='" + exam.getId() + "'>" + exam.getName() + " [座位数：" + room.getAllcount() + "]</option>");
            }
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult(null, response);
        }
    }

    //获得考场座位数
    @RequestMapping("/getseatcount")
    public void getSeatCount(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            DoBSRoom room = bsService.getRoomById(id);
            utilService.printTextResult(room.getAllcount().toString(), response);
        } catch (Exception e) {
            utilService.printTextResult("读取失败", response);
        }
    }


    //[end]

    //[start] 添加考试

    @RequestMapping("/addexam")
    public String addexam(Model model) {
        try {
            List<DoBSRoom> rooms = bsService.getRooms();
            StringBuilder roomsb = new StringBuilder();
            for (DoBSRoom room : rooms) {
                roomsb.append("<option value='" + room.getId() + "'>" + room.getName() + "</option>");
            }
            model.addAttribute("room", roomsb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Bs/examadd";
    }

    @RequestMapping(value = "/AddExamAction", method = RequestMethod.POST)
    public void AddExamAction(HttpServletRequest request, HttpServletResponse response, DoBSExam exam) {
        try {
            DoBSRoom room = bsService.getRoomById(exam.getRoomid());

            exam.setId(UUID.randomUUID().toString());
            exam.setName(room.getName() + "(" + exam.getStarttime() + "~" + exam.getEndtime().substring(11) + ")");
            utilService.addObject(exam);
            utilService.printJsonResult(true, "操作成功", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 修改考试

    @RequestMapping("/editexam")
    public String editexam(HttpServletRequest request, Model model) {
        try {
            List<DoBSRoom> rooms = bsService.getRooms();
            StringBuilder roomsb = new StringBuilder();
            for (DoBSRoom room : rooms) {
                roomsb.append("<option value='" + room.getId() + "'>" + room.getName() + "</option>");
            }
            model.addAttribute("room", roomsb);

            DoBSExam exam = bsService.getExamById(request.getParameter("id").trim());
            model.addAttribute("exam", exam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Bs/examedit";
    }

    @RequestMapping(value = "/EditExamAction", method = RequestMethod.POST)
    public void EditExamAction(HttpServletRequest request, HttpServletResponse response, DoBSExam exam) {
        try {
            DoBSRoom room = bsService.getRoomById(exam.getRoomid());
            exam.setName(room.getName() + "(" + exam.getStarttime() + "~" + exam.getEndtime().substring(11) + ")");
            utilService.editObject(exam);
            utilService.printJsonResult(true, "操作成功", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 删除考试

    @RequestMapping(value = "/DelExamAction", method = RequestMethod.POST)
    public void DelExamAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");
            if (ids == null) {
                utilService.printJsonResult(false, "请选择要删除的信息", "no", response);
            } else {
                List<DoBSExam> exams = bsService.getExams(ids);
                utilService.delList(exams);
                utilService.printJsonResult(true, "操作成功", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[end]

    //[start] 笔试安排

    @RequestMapping(value = "/PlanAction", method = RequestMethod.POST)
    public void PlanAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            String bsdate = request.getParameter("bsdate");
            String bstimes = request.getParameter("bstimes");
            String confrimTime = request.getParameter("endtime");
            String bszysx = request.getParameter("bszysx");
            String bsremark=request.getParameter("remark");
            String bsroom = request.getParameter("room");
            BaseUser usr = utilService.getSessionUser(request);
            if (usr.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    //String examid = request.getParameter("exam");
                    String[] uids = request.getParameterValues("uid");
                    if (uids == null) {
                        utilService.printJsonResult(false, "请选择参加笔试的人员", "no", response);
                    } else {
                        List<DoBSUser> addusers = new ArrayList<DoBSUser>();
                        List<DoZysx> zysxList = new ArrayList<>();
                        List<DoMSConfirm> confirmList = new ArrayList<>();
                        List editList = new ArrayList();
                        //DoBSExam exam = bsService.getExamById(examid);
                        DoBSRoom room = null;
                        String kcname = null;
                        String starttime = null;
                        String endtime = null;
                        String startdatetime = null;
                        DoBSExam doBSExam = null;

                        if (bsroom != null && bsroom.trim().length() > 0 && bsdate != null && bsdate.trim().length() > 0 && bstimes != null && bstimes.trim().length() > 0) {
                            room = bsService.getRoomById(bsroom);
                            starttime = bstimes.substring(0, 5);
                            endtime = bstimes.substring(bstimes.length() - 8, bstimes.length() - 3);
                            startdatetime = bsdate.trim() + " " + bstimes.substring(0, 8);
                            if(!StringTools.trimNotEmpty(confrimTime)) {
                                Calendar cal = CalendarUtil.parseByPatterns(startdatetime, "yyyy-MM-dd HH:mm:ss");
                                cal.add(Calendar.DATE, -2);
                                confrimTime= DateTools.toShortStr(cal.getTime());
                            }

                            kcname = room.getName() + "(" + bsdate + " " + starttime + "~" + endtime + ")";
                            Object dbexam = bsService.getBSExamByName(kcname);
                            if (dbexam == null) {

                                doBSExam = new DoBSExam();
                                doBSExam.setId(UUID.randomUUID().toString());
                                doBSExam.setRoomid(room.getId());
                                doBSExam.setName(kcname);
                                doBSExam.setStarttime(startdatetime);
                                doBSExam.setEndtime(bsdate.trim() + " " + endtime);

                            }
                        }

                        int cnt = 0;
                        for (String tid : uids){
                            DoBSUser userTemp = bsService.getBsUser(tid, fid);
                            if(userTemp != null)
                                cnt++;
                        }

                        //该考试已安排人数
                        int count = bsService.getUserCount(fid, kcname, startdatetime);

                        if (room.getAllcount() > count) {
                            //提示信息
                            String msg = null;
                            int recruittype = projectService.getpProjectById(pid).getRecruittype();
                            String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                            int cntNum = bsService.getTicketCountNew(year + String.valueOf(recruittype));
                            int ticketnum = Integer.parseInt(year + recruittype + new DecimalFormat("0000").format(cntNum));
                            ticketnum ++;
                            // 剩余座位数
                            int ct = room.getAllcount() - count;
                            for (String uid : uids) {
                                // 已经推荐到其他岗位
                                if (IsChangePost(pid, uid)) {
                                    continue;
                                }
                                DoBSUser user2 = bsService.getBsUser(uid, fid);
                                if (ct > 0) {
                                    if (user2 == null) {
                                        DoBSUser user = new DoBSUser();
                                        user.setId(UUID.randomUUID().toString());
                                        user.setAddress(room.getAddress());
                                        user.setFid(fid);
                                        user.setKcname(kcname);
                                        user.setStarttime(startdatetime);
                                        user.setNotice(EnumTools.NoticeState.未发通知.ordinal());
                                        user.setResult("-");
                                        user.setStartnum(room.getStartnum());
                                        user.setAllnum(room.getAllcount());
                                        user.setSeatnum(count + room.getStartnum());
                                        user.setTicketnum(String.valueOf(ticketnum));
                                        user.setUserid(uid);
                                        user.setRemark(bsremark);
//                                      user.setAddDate(new Date());
                                        addusers.add(user);
                                        if (bszysx != null && bszysx.trim().length() > 0) {
                                            DoZysx userzysx = utilService.getUserZysx(pid, fid, uid);
                                            if (userzysx == null) {
                                                DoZysx zysx = new DoZysx();
                                                zysx.setId(UUID.randomUUID().toString());
                                                zysx.setRemark(bszysx);
                                                zysx.setType("BS");
                                                zysx.setPid(pid);
                                                zysx.setFid(fid);
                                                zysx.setAdduser(usr.getUcode());
                                                zysx.setUserid(uid);
                                                zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                                zysxList.add(zysx);


                                            } else {
                                                userzysx.setId(UUID.randomUUID().toString());
                                                userzysx.setRemark(bszysx);
                                                userzysx.setType("BS");
                                                userzysx.setPid(pid);
                                                userzysx.setFid(fid);
                                                userzysx.setAdduser(usr.getUcode());
                                                userzysx.setUserid(uid);
                                                userzysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                                editList.add(userzysx);
                                            }
                                        }
                                        DoMSConfirm userConfirm = utilService.getMSUserConfirm(uid,"BS");
                                        if(userConfirm==null) {
                                            DoMSConfirm confirm = new DoMSConfirm();
                                            confirm.setId(UUID.randomUUID().toString());
                                            confirm.setType("BS");
                                            confirm.setMsuserid(user.getId());
                                            confirm.setEndtime(confrimTime);
                                            confirm.setIsconfirm("否");
                                            confirmList.add(confirm);
                                        }else{
                                            userConfirm.setType("BS");
                                            userConfirm.setMsuserid(user.getId());
                                            userConfirm.setEndtime(confrimTime);
                                            userConfirm.setIsconfirm("否");
                                            editList.add(userConfirm);
                                        }
                                        ticketnum++;
                                        count++;
                                        ct--;
                                    } else {
                                        user2.setAddress(room.getAddress());
                                        user2.setNotice(EnumTools.NoticeState.未发通知.ordinal());
                                        user2.setResult("-");
                                        user2.setStartnum(room.getStartnum());
                                        user2.setAllnum(room.getAllcount());
                                        if(!(user2.getFid().equals(fid) && user2.getStarttime().equals(startdatetime)&& user2.getKcname().equals(kcname))){
                                            user2.setSeatnum(count + room.getStartnum());
                                            user2.setTicketnum(String.valueOf(ticketnum));
                                            count++;
                                            ticketnum++;
                                        }
                                        user2.setFid(fid);
                                        user2.setStarttime(startdatetime);
                                        user2.setKcname(kcname);
                                        user2.setUserid(uid);
                                        user2.setRemark(bsremark);
//                                        user2.setAddDate(new Date());
                                        editList.add(user2);
                                        if (bszysx != null && bszysx.trim().length() > 0) {
                                            DoZysx doZysx = utilService.getUserZysx(pid, fid, uid);
                                            if (doZysx != null) {
                                                doZysx.setRemark(bszysx);
                                                doZysx.setType("BS");
                                                doZysx.setPid(pid);
                                                doZysx.setFid(fid);
                                                doZysx.setAdduser(usr.getUcode());
                                                doZysx.setUserid(uid);
                                                doZysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                                editList.add(doZysx);
                                            } else {
                                                DoZysx zysx = new DoZysx();
                                                zysx.setId(UUID.randomUUID().toString());
                                                zysx.setRemark(bszysx);
                                                zysx.setType("BS");
                                                zysx.setPid(pid);
                                                zysx.setFid(fid);
                                                zysx.setAdduser(usr.getUcode());
                                                zysx.setUserid(uid);
                                                zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                                zysxList.add(zysx);
                                            }
                                        }

                                        DoMSConfirm userConfirm = utilService.getMSUserConfirm(uid,"BS");
                                        if(userConfirm==null) {
                                            DoMSConfirm confirm = new DoMSConfirm();
                                            confirm.setId(UUID.randomUUID().toString());
                                            confirm.setType("BS");
                                            confirm.setMsuserid(uid);
                                            confirm.setEndtime(confrimTime);
                                            confirm.setIsconfirm("否");
                                            confirmList.add(confirm);
                                        }else{
                                            userConfirm.setType("BS");
                                            userConfirm.setMsuserid(uid);
                                            userConfirm.setEndtime(confrimTime);
                                            userConfirm.setIsconfirm("否");
                                            userConfirm.setConfirmtime(null);
                                            editList.add(userConfirm);
                                        }
                                        ct--;
                                    }
                                } else {
                                    msg = "所选考试座位数有限，部分人员未成功安排，请选择其他考试";
                                }
                            }
                            if (addusers.size() > 0 || editList.size() > 0) {
                                if (doBSExam != null) {
                                    utilService.addObject(doBSExam);
                                }

                                utilService.addList(addusers);
                                if (zysxList.size() > 0) {
                                    utilService.addList(zysxList);
                                }
                                if (confirmList.size() > 0) {
                                    utilService.addList(confirmList);
                                }

                                if (editList.size() > 0) {
                                    utilService.editList(editList);
                                }
                                utilService.printJsonResult(true, "操作成功!" + (msg == null ? "" : msg), "no", response);
                            } else {
                                utilService.printJsonResult(false, "当前选中信息不支持此操作！", "no", response);
                            }

                        } else {
                            utilService.printJsonResult(false, "所选考试已无剩余座位！", "no", response);
                        }
                    }

                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "", response);
        }

    }

    //一键分配
    @RequestMapping(value = "/AssignmentAction", method = RequestMethod.POST)
    public void AssignmentAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String jname = request.getParameter("jname");
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            String bsdate = request.getParameter("bsdate");
            String bstimes = request.getParameter("bstimes");
            String bsroom = request.getParameter("room");
            String bszysx = request.getParameter("bszysx");
            String address = request.getParameter("address");


            String start = bsdate + " " + bstimes.substring(0, 5);
            String end = bsdate + " " + bstimes.substring(bstimes.length() - 8, bstimes.length() - 3);
            List rooms = null;
            List<Map<String, String>> result = new ArrayList<Map<String, String>>();
            try {
                if(StringTools.trimNotEmpty(bsroom)&&bsroom.indexOf(",")>0){
                    String[] bsroomss=bsroom.split(",");
                    String ts="";
                    for (int i = 0; i < bsroomss.length; i++) {
                        ts+= "'"+bsroomss[i]+"',";
                    }
                    String ts1=ts.substring(0,ts.length()-1);
                    rooms=bsService.getCanUseRoomByRoomId(start,end,ts1);
                }else {
                    rooms = bsService.getCanUseRoomByAddress(start, end, address);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            List<DoZysx> zysxList = new ArrayList<>();
            List editList = new ArrayList();
            BaseUser usr = utilService.getSessionUser(request);
            if (usr.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    List<DoBSUser> addusers = new ArrayList<DoBSUser>();
                    String kcname = null;
                    String starttime = null;
                    String endtime = null;
                    String startdatetime = null;
                    int recruittype = projectService.getpProjectById(pid).getRecruittype();
                    starttime = bstimes.substring(0, 5);
                    endtime = bstimes.substring(bstimes.length() - 8, bstimes.length() - 3);
                    startdatetime = bsdate.trim() + " " + bstimes.substring(0, 5);
                    List<String> users = bsService.FastPlan(fid, pid, jname);
                    int all = users.size();
                    int userall = all;
                    int ready = 0;
                    String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                    //int ticketnum = Integer.parseInt(year + recruittype + new DecimalFormat("0000").format(bsService.getTicketCount(year + String.valueOf(recruittype))));
                    int ticketnum = Integer.parseInt(year  + new DecimalFormat("00000").format(bsService.getTicketCount(year + String.valueOf(recruittype))));
                    //System.out.println(year + String.valueOf(recruittype) + "============" + ticketnum);
                    //System.out.println(bsService.getTicketCount(year + String.valueOf(recruittype)));
                    for (int j = 0; j < rooms.size(); j++) {
                        Object[] nowroom = (Object[]) rooms.get(j);
                        kcname = nowroom[1].toString() + "(" + bsdate + " " + starttime + "~" + endtime + ")";
                        int allnum = Integer.parseInt(nowroom[2].toString());
                        if (all<=0){
                            break;
                        }
                        if (allnum > all) {
                            List setnum = new ArrayList();
                            int set;
                            for (int i = 0; i < all; i++) {
                                for (; ; ) {
                                    set = (int) (1 + Math.random() * (all - 1 + 1));
                                    if (!setnum.contains(set)) {
                                        setnum.add(set);
                                        break;
                                    }
                                    ;
                                }
                                DoBSUser user = new DoBSUser();
                                user.setId(UUID.randomUUID().toString());
                                user.setAddress(nowroom[1].toString());
                                user.setFid(fid);
                                user.setKcname(kcname);
                                user.setStarttime(startdatetime);
                                user.setNotice(EnumTools.NoticeState.未发通知.ordinal());
                                user.setResult("-");
                                user.setStartnum(1);
                                user.setAllnum(all);
                                user.setSeatnum(set);
                                user.setTicketnum(String.valueOf(ticketnum + set + ready));
                                user.setUserid(users.get(i+ready));
                                user.setRemark(request.getParameter("remark"));
                                addusers.add(user);
                                if (bszysx != null && bszysx.trim().length() > 0) {
                                    DoZysx doZysx = utilService.getUserZysx(pid, fid, users.get(i + ready));
                                    if (doZysx != null) {
                                        doZysx.setRemark(bszysx);
                                        doZysx.setType("BS");
                                        doZysx.setPid(pid);
                                        doZysx.setFid(fid);
                                        doZysx.setAdduser(usr.getUcode());
                                        doZysx.setUserid(users.get(i + ready));
                                        doZysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        editList.add(doZysx);
                                    } else {
                                        DoZysx zysx = new DoZysx();
                                        zysx.setId(UUID.randomUUID().toString());
                                        zysx.setRemark(bszysx);
                                        zysx.setType("BS");
                                        zysx.setPid(pid);
                                        zysx.setFid(fid);
                                        zysx.setAdduser(usr.getUcode());
                                        zysx.setUserid(users.get(i + ready));
                                        zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        zysxList.add(zysx);
                                    }
                                }
                            }
                            DoBSExam doBSExam = new DoBSExam();
                            doBSExam = new DoBSExam();
                            doBSExam.setId(UUID.randomUUID().toString());
                            doBSExam.setRoomid(nowroom[0].toString());
                            doBSExam.setName(kcname);
                            doBSExam.setStarttime(startdatetime);
                            doBSExam.setEndtime(bsdate.trim() + " " + endtime);
                            utilService.addObject(doBSExam);
                            all = all - allnum;
                            ready += allnum;
                            break;
                        } else if (allnum <= all) {
                            List setnum = new ArrayList();
                            int set;
                            for (int i = 0; i < allnum; i++) {
                                for (; ; ) {
                                    set = (int) (1 + Math.random() * (allnum - 1 + 1));
                                    if (!setnum.contains(set)) {
                                        setnum.add(set);
                                        break;
                                    }
                                    ;
                                }
                                DoBSUser user = new DoBSUser();
                                user.setId(UUID.randomUUID().toString());
                                user.setAddress(nowroom[1].toString());
                                user.setFid(fid);
                                user.setKcname(kcname);
                                user.setStarttime(startdatetime);
                                user.setNotice(EnumTools.NoticeState.未发通知.ordinal());
                                user.setResult("-");
                                user.setStartnum(1);
                                user.setAllnum(allnum);
                                user.setSeatnum(set);
                                user.setTicketnum(String.valueOf(ticketnum + set + ready));
                                user.setUserid(users.get(i + ready));
                                user.setRemark(request.getParameter("remark"));
                                addusers.add(user);
                                if (bszysx != null && bszysx.trim().length() > 0) {
                                    DoZysx doZysx = utilService.getUserZysx(pid, fid, users.get(i + ready));
                                    if (doZysx != null) {
                                        doZysx.setRemark(bszysx);
                                        doZysx.setType("BS");
                                        doZysx.setPid(pid);
                                        doZysx.setFid(fid);
                                        doZysx.setAdduser(usr.getUcode());
                                        doZysx.setUserid(users.get(i + ready));
                                        doZysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        editList.add(doZysx);
                                    } else {
                                        DoZysx zysx = new DoZysx();
                                        zysx.setId(UUID.randomUUID().toString());
                                        zysx.setRemark(bszysx);
                                        zysx.setType("BS");
                                        zysx.setPid(pid);
                                        zysx.setFid(fid);
                                        zysx.setAdduser(usr.getUcode());
                                        zysx.setUserid(users.get(i));
                                        zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        zysxList.add(zysx);
                                    }
                                }
                            }

                            DoBSExam doBSExam = new DoBSExam();
                            doBSExam = new DoBSExam();
                            doBSExam.setId(UUID.randomUUID().toString());
                            doBSExam.setRoomid(nowroom[0].toString());
                            doBSExam.setName(kcname);
                            doBSExam.setStarttime(startdatetime);
                            doBSExam.setEndtime(bsdate.trim() + " " + endtime);
                            utilService.addObject(doBSExam);
                            all = all - allnum;
                            ready += allnum;
                        }
                    }
                    if (zysxList.size() > 0) {
                        utilService.addList(zysxList);
                    }

                    if (editList.size() > 0) {
                        utilService.editList(editList);
                    }
                    utilService.addList(addusers);
                    String msg;
                    if (all<=0){
                       msg=jname+"岗位笔试安排如下：<br/>" +
                                "本次安排人数【"+userall+"人】" +
                                "已安排人数【"+userall+"人】" +
                                "一键安排剩余座位数【"+(ready - userall)+"人】";
                    }else{
                       msg="考场不够<br/>" + "本次" + jname+"岗位笔试安排如下：<br/>" +
                                "本次安排人数【"+ready+"人】" +
                                "已安排人数【"+ready+"人】" +
                                "一键安排剩余座位数【"+ 0 +"人】";
                    }
                    utilService.printJsonResult(false, msg, "no", response);
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "", response);
        }

    }

    //[end]

    //[start] 导出笔试安排

    @RequestMapping("/exportplan")
    public void exportPlan(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            codedFileName = java.net.URLEncoder.encode("笔试安排", "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();

            //[start] 笔试安排表头

            HSSFRow headrow = sheet.createRow(0);//创建一行
            HSSFCell headcel0 = headrow.createCell(0);
            headcel0.setCellValue(new HSSFRichTextString("笔试编号"));
            HSSFCell headcel1 = headrow.createCell(1);
            headcel1.setCellValue(new HSSFRichTextString("姓名"));
            HSSFCell headcel2 = headrow.createCell(2);
            headcel2.setCellValue(new HSSFRichTextString("性别"));
            HSSFCell headcel3 = headrow.createCell(3);
            headcel3.setCellValue(new HSSFRichTextString("身份证号"));
            HSSFCell headcel4 = headrow.createCell(4);
            headcel4.setCellValue(new HSSFRichTextString("手机"));
            HSSFCell headcel5 = headrow.createCell(5);
            headcel5.setCellValue(new HSSFRichTextString("应聘岗位"));
            HSSFCell headcel6 = headrow.createCell(6);
            headcel6.setCellValue(new HSSFRichTextString("笔试场地"));
            HSSFCell headcel7 = headrow.createCell(7);
            headcel7.setCellValue(new HSSFRichTextString("准考证号"));
            HSSFCell headcel8 = headrow.createCell(8);
            headcel8.setCellValue(new HSSFRichTextString("座位号"));
            HSSFCell headcel9 = headrow.createCell(9);
            headcel9.setCellValue(new HSSFRichTextString("综合素质"));
            HSSFCell headcel10 = headrow.createCell(10);
            headcel10.setCellValue(new HSSFRichTextString("综合素质结果"));
            HSSFCell headcel11 = headrow.createCell(11);
            headcel11.setCellValue(new HSSFRichTextString("个性测评"));
            HSSFCell headcel12 = headrow.createCell(12);
            headcel12.setCellValue(new HSSFRichTextString("个性测评结果"));
            HSSFCell headcel13 = headrow.createCell(13);
            headcel13.setCellValue(new HSSFRichTextString("专业测评"));
            HSSFCell headcel14 = headrow.createCell(14);
            headcel14.setCellValue(new HSSFRichTextString("专业测评结果"));
            HSSFCell headcel15 = headrow.createCell(15);
            headcel15.setCellValue(new HSSFRichTextString("本轮成绩"));
            HSSFCell headcel16 = headrow.createCell(16);
            headcel16.setCellValue(new HSSFRichTextString("成绩评定"));
            HSSFCell headcel17 = headrow.createCell(17);
            headcel17.setCellValue(new HSSFRichTextString("备注"));
            //[end]

            String[] _uids = request.getParameterValues("uid");
            String pid = request.getParameter("pid").trim();
            List<String> us = new ArrayList<String>();
            for (String uid : _uids) {
                // 已经推荐到其他岗位
                if (IsChangePost(pid, uid)) {
                    continue;
                }
                us.add(uid);
            }

            if (us.size() > 0) {
                String[] uids = (String[]) us.toArray(new String[us.size()]);

                String fid = request.getParameter("fid").trim();
                ProjectInfo project = projectService.getProjectInfo(fid);

                List<Object[]> objs = bsService.getBsPlan(fid, uids, project.getRecruittype());
                int i = 1;
                for (Object[] obj : objs) {
                    HSSFRow row = sheet.createRow(i);//创建一行
                    for (int j = 0; j < 16; j++) {
                        HSSFCell cell = row.createCell(j);//创建一列
                        //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellType(CellType.STRING);
                        cell.setCellValue(new HSSFRichTextString(obj[j] == null ? "" : obj[j].toString()));
                    }
                    i++;
                }
            }
            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }

    //[end]

    //[start] 导出准考证

    @RequestMapping("/exportticket")
    public void exportTicket(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            codedFileName = java.net.URLEncoder.encode("笔试准考证", "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();

            //[start] 表头

            HSSFRow headrow = sheet.createRow(0);//创建一行
            HSSFCell headcel0 = headrow.createCell(0);
            headcel0.setCellValue(new HSSFRichTextString("姓名"));
            HSSFCell headcel1 = headrow.createCell(1);
            headcel1.setCellValue(new HSSFRichTextString("身份证号"));
            HSSFCell headcel2 = headrow.createCell(2);
            headcel2.setCellValue(new HSSFRichTextString("性别"));
            HSSFCell headcel3 = headrow.createCell(3);
            headcel3.setCellValue(new HSSFRichTextString("手机"));
            HSSFCell headcel4 = headrow.createCell(4);
            headcel4.setCellValue(new HSSFRichTextString("应聘职位"));
            HSSFCell headcel5 = headrow.createCell(5);
            headcel5.setCellValue(new HSSFRichTextString("笔试场地"));
            HSSFCell headcel6 = headrow.createCell(6);
            headcel6.setCellValue(new HSSFRichTextString("准考证号"));
            HSSFCell headcel7 = headrow.createCell(7);
            headcel7.setCellValue(new HSSFRichTextString("座位号"));

            //[end]

            String[] _uids = request.getParameterValues("uid");
            String pid = request.getParameter("pid").trim();
            List<String> us = new ArrayList<String>();
            for (String uid : _uids) {
                // 已经推荐到其他岗位
                if (IsChangePost(pid, uid)) {
                    continue;
                }
                us.add(uid);
            }

            if (us.size() > 0) {
                String[] uids = (String[]) us.toArray(new String[us.size()]);

                String fid = request.getParameter("fid").trim();
                ProjectInfo project = projectService.getProjectInfo(fid);

                List<Object[]> objs = bsService.getBsTicket(fid, uids, project.getRecruittype());
                int i = 1;
                for (Object[] obj : objs) {
                    HSSFRow row = sheet.createRow(i);//创建一行
                    for (int j = 0; j < 8; j++) {
                        HSSFCell cell = row.createCell(j);//创建一列
                       // cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        cell.setCellType(CellType.STRING);
                        cell.setCellValue(new HSSFRichTextString(obj[j] == null ? "" : obj[j].toString()));
                    }
                    i++;
                }
            }
            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }

    //[end]

    //[start] 导入笔试成绩

    @RequestMapping("/import")
    public String Import(HttpServletRequest request, Model model) {
        try {
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Bs/import";
    }


    //上传Excel事件
    @RequestMapping(value = {"/ImportAction"}, method = RequestMethod.POST)
    public void ImportAction(@RequestParam("excel") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {
            String exname = StringTools.getFileExtension(file.getOriginalFilename());//扩展名（.xxx）
            if (exname.equals(".xls") || exname.equalsIgnoreCase(".xlsx")) {
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码

                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        //改为自动识别列名并返回导出结果
                        /*List<DoBSUser> users = getAllByExcel(fid, file.getInputStream());
                        if (users != null) {
                            utilService.editList(users);
                            utilService.printJsonResult(true, "操作成功", "no", response);
                        } else {
                            utilService.printJsonResult(false, "无符合条件的信息！", "no", response);
                        }*/

                        DataTable dataTable = importBsUserByExcel(file, fid);
                        if(dataTable !=null){
                            boolean getflag = false;
                            for(int i = 0;i<dataTable.Columns.size();i++){
                                if(dataTable.Columns.get(i).ColumnName.equals("身份证号")){
                                    getflag = true;
                                    break;
                                }
                            }

                            if(getflag){
                                org.apache.poi.ss.usermodel.Workbook reusultbook = ExcelHelper.DataTableToExcel(dataTable, "笔试成绩导入结果");
                                String fileName = file.getOriginalFilename();
                                //response.setHeader("content-disposition", "attachment;filename=" + fileName.substring(0,fileName.lastIndexOf(".")) + "导入结果.xls");
                                //(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())).toString()
                                String rfilename = fileName.substring(0, fileName.lastIndexOf(".")) + "导入结果"+".xls";
                                String uploadPath = request.getServletContext().getRealPath("\\resources\\upload");
                                String rfilepath = uploadPath + "\\excelresult";
                                File rdir = new File(rfilepath);

                                if (rdir.exists()) {
                                    String[] filelist = rdir.list();
                                    for (int i = 0; i < filelist.length; i++) {
                                        File readfile = new File(rfilepath + "\\" + filelist[i]);
                                        readfile.delete();
                                    }
                                } else {
                                    boolean bmkdir = rdir.mkdir();
                                    if (!bmkdir) {
                                        rdir.mkdirs();
                                    }
                                }
                                File rfile = new File(rfilepath + "\\" + rfilename);
                                if (rfile.createNewFile()) {
                                    FileOutputStream fileOutputStream = new FileOutputStream(rfile);
                                    reusultbook.write(fileOutputStream);
                                }
                                utilService.printJsonResult(true, "操作成功！", request.getContextPath() + "/resources/upload/excelresult/" + rfilename, response);
                            }else {
                                utilService.printJsonResult(false, "无法识别身份证号列！", "no", response);
                            }
                        } else {
                            utilService.printJsonResult(false, "无符合条件的信息！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "只能上传后缀为：xls和xlsx的Excel文件", "no", response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }

    }

    private List<DoBSUser> getAllByExcel(String fid, InputStream inputStream) {
        try {
            Workbook rwb = Workbook.getWorkbook(inputStream);
            Sheet rs = rwb.getSheet(0);//得到第一个工作表中的数据(人员信息)
            int rows = rs.getRows();//得到所有的行
            List<DoBSUser> users = new ArrayList<DoBSUser>();
            for (int i = 1; i < rows; i++) {
                if (rs.getCell(0, i).getContents().length() != 0) {
                    String id = rs.getCell(0, i).getContents().trim();
                    DoBSUser bsUser = bsService.getBsUser(id);
                    if (bsUser != null
                            /*&& bsUser.getNotice() == EnumTools.NoticeState.已发通知.ordinal()*/ && bsUser.getFid().equals(fid)) {
                        bsUser.setZhszpoint(rs.getCell(9, i).getContents().trim());
                        bsUser.setZhszresult(rs.getCell(10, i).getContents().trim());
                        bsUser.setGxcppoint(rs.getCell(11, i).getContents().trim());
                        bsUser.setGxcpresult(rs.getCell(12, i).getContents().trim());
                        bsUser.setZycppoint(rs.getCell(13, i).getContents().trim());
                        bsUser.setZycpresult(rs.getCell(14, i).getContents().trim());
                        bsUser.setPoint(rs.getCell(15, i).getContents().trim());
                        bsUser.setResult(rs.getCell(16, i).getContents().trim());
                        bsUser.setPointdate(new Date());

                        users.add(bsUser);
                    }
                } else {
                    break;
                }
            }
            return users;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    private DataTable importBsUserByExcel(MultipartFile file, String fid) throws Exception {
        DataTable dataTable = ExcelHelper.ReadExcelToDataTable(file);
        DecimalFormat df = new DecimalFormat("0");
        if (dataTable != null) {
            for (DataRow row : dataTable.Rows) {
                if (row.getValue("准考证号") != null) {
                    double d = Double.parseDouble(row.getValue("准考证号").toString());
                    String ticketnum = df.format(d);
                    String jname = row.getValue("应聘岗位").toString();
                    List<DoBSUser> bsUsers = bsService.getBsUserByTicketnumAndJname(ticketnum, jname, fid);
                    if (bsUsers != null && bsUsers.size() > 0) {
                        DoBSUser bsUser = bsUsers.get(0);
                        /*if (row.getValue("A能力测验结果") != null) {
                            bsUser.setZhszpoint(row.getValue("A能力测验结果").toString().trim());
                        }
                        if (row.getValue("A能力等级") != null) {
                            bsUser.setZhszresult(row.getValue("A能力等级").toString().trim());
                        }
                        if (row.getValue("B个性匹配度") != null) {
                            bsUser.setGxcppoint(row.getValue("B个性匹配度").toString().trim());
                        }
                        if (row.getValue("B个性匹配度评估") != null) {
                            bsUser.setGxcpresult(row.getValue("B个性匹配度评估").toString().trim());
                        }
                        if (row.getValue("测评总分") != null) {
                            bsUser.setPoint(row.getValue("测评总分").toString().trim());
                        }
                        if (row.getValue("测评总体结果") != null) {
                            bsUser.setResult(row.getValue("测评总体结果").toString().trim());
                        }
                        if (row.getValue("笔试成绩") != null) {
                            bsUser.setPoint(row.getValue("笔试成绩").toString().trim());
                        }
                        if (row.getValue("笔试结果") != null) {
                            bsUser.setResult(row.getValue("笔试结果").toString().trim());
                        }*/
                        if (row.getValue("综合素质") != null) {
                            bsUser.setZhszpoint(row.getValue("综合素质").toString().trim());
                        }
                        if (row.getValue("综合素质结果") != null) {
                            bsUser.setZhszresult(row.getValue("综合素质结果").toString().trim());
                        }
                        if (row.getValue("个性测评") != null) {
                            bsUser.setGxcppoint(row.getValue("个性测评").toString().trim());
                        }
                        if (row.getValue("个性测评结果") != null) {
                            bsUser.setGxcpresult(row.getValue("个性测评结果").toString().trim());
                        }

                        if (row.getValue("专业测评") != null) {
                            bsUser.setZycppoint(row.getValue("专业测评").toString().trim());
                        }
                        if (row.getValue("专业测评结果") != null) {
                            bsUser.setZycpresult(row.getValue("专业测评结果").toString().trim());
                        }

                        if (row.getValue("本轮成绩") != null) {
                            bsUser.setPoint(row.getValue("本轮成绩").toString().trim());
                        }
                        if (row.getValue("成绩评定") != null) {
                            bsUser.setResult(row.getValue("成绩评定").toString().trim());
                        }


                        if (row.getValue("备注") != null) {
                            bsUser.setRemark(row.getValue("备注").toString().trim());
                        }
                        bsUser.setPointdate(new Date());
                        utilService.editObject(bsUser);
                        row.setValue("导入状态", "已导入");
                    }
                }
            }
        }
        return dataTable;
    }

    //[end]

    //[start] 发短信

    @RequestMapping(value = "/MsgAction", method = RequestMethod.POST)
    public void MsgAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    String dxnr = request.getParameter("dxnr");
                    String dxmb = request.getParameter("dxmb");
                    List<Map<String, String>> msgs = new ArrayList<Map<String, String>>();

                    String[] uids = request.getParameterValues("uid");
                    if (uids == null) {
                        utilService.printJsonResult(false, "请选择参加笔试的人员信息！", "no", response);
                        return;
                    }
                    ProjectInfo project = projectService.getpProjectById(pid);
                    List<Object[]> users = bsService.getBsUser(uids, fid, project.getRecruittype());
                    List<String> sqls = new ArrayList<String>();
                    List<String> errorsqls = new ArrayList<String>();
                    for (Object[] user : users) {
                        //u.id,r.name,r.tel,u.starttime,u.address,u.notice
                            //逐条发送短信
                        String messageResult;
                            if (StringTools.trimNotEmpty(dxmb)){
                                if (dxmb.contains("fulltext")){
                                    messageResult = MsgUtils.sendSMSByTemplate(user[2].toString(),"1604547007951CUb");
                                }else {
                                    messageResult = MsgUtils.sendSMSByTemplate(user[2].toString());
                                }
                            }else {
                                messageResult = MsgUtils.sendSMSByTemplate(user[2].toString());
                            }


                        JSONObject object = JSONObject.fromObject(messageResult);
                            //if(object.getInt("error_code")==0){
                            if(messageResult.indexOf("success")>=0){
                                sqls.add("update DoBS_User set notice='" + EnumTools.NoticeState.已发通知.ordinal() + "' where id='" + user[0] + "'");

                            }else{
                                errorsqls.add("update DoBS_User set notice='" + EnumTools.NoticeState.未发通知.ordinal() + "' where id='" + user[0] + "'");
                            }

                            //sqls.add("update DoBS_User set notice='" + EnumTools.NoticeState.已发通知.ordinal() + "' where id='" + user[0] + "'");

                            //-------------短信----------------
                           /* Map<String, String> _map = new HashMap<String, String>();
                            _map.put("tel", user[2].toString());
                            _map.put("cont", dxnr.replace("{姓名}", user[1].toString()).replace("{时间}", user[3].toString()).replace("{地点}", user[4].toString()));
                            msgs.add(_map);*/
                    }
                    if (sqls.size() +errorsqls.size()> 0) {
                        utilService.editSqls(sqls);
                        utilService.editSqls(errorsqls);
                        utilService.printJsonResult(true, "操作成功！发送成功:"+sqls.size()+" 条短信，失败："+errorsqls.size()+" 条", "no", response);

                        /*if (PhoneTools.sendMsg(msgs, messageConfig.getUsername(), messageConfig.getPassword(), messageConfig.getHost())) {
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "短信发送失败！", "no", response);
                        }*/
                    } else {
                        utilService.printJsonResult(false, "无可执行此操作的信息！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }

            utilService.printJsonResult(true, "操作成功", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    @RequestMapping("/getMsg")
    public void getMsgCont(HttpServletRequest request, HttpServletResponse response) {
        try {
            String msg = utilService.getConfig(request.getParameter("code").trim());
            utilService.printTextResult(msg, response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }

//    @RequestMapping("/assignment")
//    public String DownSign(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
//        try {
//            String pid = request.getParameter("pid").trim();//招聘方案ID
//            String fid = request.getParameter("fid").trim();//招聘流程ID
//            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
//            //招聘岗位
//            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(pid);
//            List<DoBSRoom> rooms = bsService.getRooms();
//            StringBuilder roomsb = new StringBuilder();
//            roomsb.append("<option value=''>请选择</option>");
//            for (DoBSRoom room : rooms) {
//                roomsb.append("<option value='" + room.getId() + "'>" + room.getName() +"["+room.getAllcount()+"人]"+ "</option>");
//            }
//            model.addAttribute("room", roomsb);
//            model.addAttribute("jobs",projectJobs);
//            model.addAttribute("pid", pid);
//            model.addAttribute("fid", fid);
//            model.addAttribute("deptcode", deptcode);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "/Do/Bs/assignment";
//    }


    @ResponseBody
    @RequestMapping("/getAddress")
    public List getAddress(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        List<String> result = new ArrayList<>();
        result = bsService.getRoomsAddress();
        //System.out.println("===============address" + result.size());
        return result;
    }

    @RequestMapping("/assignment")
    public String Assignment(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        try {
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            //招聘岗位
            List<ProjectInfoJobs> projectJobs = utilService.getProjectJobs(pid);
            model.addAttribute("jobs", projectJobs);
            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Bs/assignment";
    }


    //[end]

    //[start] 公共方法

    /**
     * 是否已经推荐到其他岗位
     *
     * @param pid 招聘方案ID
     * @param uid 简历ID
     * @return true:已推荐、false:未推荐
     */
    private boolean IsChangePost(String pid, String uid) {
        try {
            if (pid.startsWith("A_")) {
                DUserResume resume = szService.getResume(uid);
                if (resume.getNrid() != null) return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    //[end]

    @ResponseBody
    @RequestMapping(value = "/getCanUseRoom")
    public List getCanUseRoom(String date, String times) {
        String startTime = date + " " + times.substring(0, 5);
        String endTime = date + " " + times.substring(times.length() - 8, times.length() - 3);
        List rooms = null;
        List result = new ArrayList();
        try {
            rooms = bsService.getCanUseRoom(startTime, endTime);
            if (rooms != null && rooms.size() > 0) {
                for (int i = 0; i < rooms.size(); i++) {
                    Object[] room = (Object[]) rooms.get(i);
                    Map<String, String> stringMap = new HashMap<>();
                    stringMap.put("id", room[0].toString());
                    stringMap.put("name", room[1].toString());
                    stringMap.put("kbrs", room[2].toString());
                    result.add(stringMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getCanUseRoomByAddress")
    public List<Map<String, String>> getCanUseRoomByAddress(String date, String times, String address, Model model) {
        String startTime = date + " " + times.substring(0, 5);
        String endTime = date + " " + times.substring(times.length() - 8, times.length() - 3);
        List rooms = null;
        List<Map<String, String>> result = new ArrayList<Map<String, String>>();
        try {
            rooms = bsService.getCanUseRoomByAddress(startTime, endTime, address);
            if(rooms.size()==0)
                model.addAttribute("roomAll", "");
            else
                model.addAttribute("roomAll", rooms.toArray());
            if (rooms != null && rooms.size() > 0) {
                for (int i = 0; i < rooms.size(); i++) {
                    Object[] room = (Object[]) rooms.get(i);
                    if (Integer.parseInt(room[3].toString()) == Integer.parseInt(room[2].toString())) {
                        System.out.println(Integer.parseInt(room[3].toString()) + "====================" + Integer.parseInt(room[2].toString()));
                        Map<String, String> stringMap = new HashMap<>();
                        stringMap.put("id", room[0].toString());
                        stringMap.put("name", room[1].toString());
                        stringMap.put("kbrs", room[2].toString());
                        result.add(stringMap);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
